import React, { useEffect } from 'react'
import ParticlesBg from 'particles-bg'
import { Button, Message, Form, Input } from 'antd';
import style from './login.less'
import { rm } from '../utils/index'
import { userLogin, getCode, getUserInfo } from '@/api/user'
import { useHistory } from 'umi'

// 登录
// 获取用户信息
// 根据用户信息获取对应权限

const onFinishFailed = (errorInfo: any) => {
    Message.error("请输入必填项")
};

export default function login() {
    const router = useHistory()

    const onFinish = (values: any) => {
        userLogin(values).then(res => {
            const token = res.data.token
            localStorage.setItem("token", token)
            // 存储用户信息
            getUserInfo().then(res => {
                localStorage.setItem("userInfo", JSON.stringify(res.data.data))
                router.push("/")
            })
        })
    };

    const code = () => {
        const c1 = document.getElementById("c1")
        getCode().then(res => {
            rm(c1, res.data.yzm)
        })
    }

    useEffect(() => {
        code()
    }, [])
    return (
        <div>
            <div className={style.card}>
                <Form
                    name="basic"
                    wrapperCol={{ span: 24 }}
                    style={{ maxWidth: 600 }}
                    initialValues={{ remember: true }}
                    onFinish={onFinish}
                    onFinishFailed={onFinishFailed}
                    autoComplete="off"
                >
                    <Form.Item
                        name="user"
                        rules={[{ required: true, message: 'Please input your username!' }]}
                    >
                        <Input />
                    </Form.Item>

                    <Form.Item
                        name="pwd"
                        rules={[{ required: true, message: 'Please input your password!' }]}
                    >
                        <Input.Password />
                    </Form.Item>

                    <Form.Item
                        name="rule"
                        rules={[{ required: true, message: 'Please input your 验证码!' }]}
                    >
                        <div style={{
                            display: "flex"
                        }}>
                            <Input />
                            <canvas onClick={code} id='c1'></canvas>
                        </div>
                    </Form.Item>


                    <Form.Item wrapperCol={{ span: 24 }}>
                        <Button style={{
                            width: "100%"
                        }} type="primary" htmlType="submit">
                            登录
                        </Button>
                    </Form.Item>
                </Form>
            </div>
            <ParticlesBg type="circle" bg={true} />
        </div>
    )
}
